<?php

namespace App\Backend\Http\Controllers;

use App\Article;
use App\Backend\Http\Ql\CircleQueryService;
use App\Cat;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;

class ArticleController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Response
     */
    public function index($type)
    {
        $data['cats'] = Cat::where('type',$type)->get();
        $data['articles'] = Article::where('is_del',0)->orderBy('created_at','desc')->paginate(20);
        $data['type'] = 1;
        return view('backend::article.article',$data);
    }
    /**
     * Show the form for creating a new resource.
     * @return Response
     */
    public function create($id,$type)
    {
        $data['article'] = Article::find($id);
        $cats= Cat::where('type',7)->get();
        $data['cats'] = collect($cats)->groupBy('father_id');
        $data['style'] = Cat::where('type',8)->get();
        $data['type'] = 7;
        if($type == 1){
            return view('backend::article.create',$data);
        }elseif($type == 2){
            return view('backend::article.showquery',$data);
        }else{
            return view('backend::article.admincreate',$data);
        }
    }

    /**
     * Store a newly created resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function store(Request $request)
    {
        $data = $request->validate([
            'id'=>'',
            'title'=>'required',
            'url'=>'',
            'file'=>'required',
            'image'=>'required',
            'cat_id1'=>'required',
            'cat_id2'=>'required',
            'style'=>'required',
            'status'=>'required',
            'type'=>'required',
            'content'=>'',
        ]);
        //采集论坛的帖子
        if($data['type'] == 2){
            $data['content'] = str_replace('src','data-original',$data['content']);
//        后台上传的案例
        }elseif($data['type'] == 3){
            $data['content'] = str_replace('src','class="lazy" data-original',$data['content']);
        }
        if($data['id']){
            Article::where('id',$data['id'])->update($data);
        }else{
            Article::create($data);
        }
        return redirect('/backend/article/7');
    }


    /**
     * Show the form for editing the specified resource.
     * @return Response
     */
    public function edit()
    {
        return view('backend::edit');
    }


    public function query(Request $request)
    {
        $circle = new CircleQueryService();
        return  $circle->article($request->url);
    }

    /**
     * Remove the specified resource from storage.
     * @return Response
     */
    public function destroy($id)
    {
        Article::where('id',$id)->update(['is_del'=>1]);
        return redirect('/backend/article/7');
    }
}
